const http = require('http')
const path = require('path')
const fs = require('fs')
const mime = require('mime')
const zlib = require('zlib')

const server = http.createServer((req, res) => {
  let filePath = path.resolve(__dirname, path.join('www', req.url))
  if (fs.existsSync(filePath)) {
    const stat = fs.statSync(filePath)
    if (stat.isDirectory()) {
      filePath = path.join(filePath, '/index.html')
    }

    if (fs.existsSync(filePath)) {
      const { ext } = path.parse(filePath)
      const stat = fs.statSync(filePath)
      const timeStamp = req.headers['if-modified-since']
      let status = 200

      if (timeStamp && Number(timeStamp) === stat.mtimeMs) {
        status = 304
      }

      const mimeType = mime.getType(ext)
      const responseHeaders = {
        'Content-Type': mimeType,
        'Cache-control': 'max-age=86400',
        'Last-Modified': stat.mtimeMs
      }  
      const compress = /^(text|application)\//.test(mimeType)  // text/palin   text/html   application/json
      if (compress) {
        // responseHeaders['Content-encoding'] = 'deflate'
        acceptEncoding.split((/\s*,\s*/)).some(encoding=>{
            if(encoding === 'gzip'){
                responseHeaders['Content-encoding'] = 'gzip'
                return true
            }
            if(encoding === 'deflate'){
                responseHeaders['Content-encoding'] = 'deflate'
                return true
            }
            if(encoding === 'br'){
                responseHeaders['Content-encoding'] = 'br'
                return true
            }
            return false


        })
      }
      res.writeHead(status, responseHeaders)
      const compressionEncoding=responseHeaders['Content-encoding']

      if (status === 200) {
        const fileStream = fs.createReadStream(filePath)
        if(compress&&compressionEncoding){
            let comp=null
            if(compressionEncoding === 'gzip'){
                comp=zlib.createGzip()
            }
           else if(compressionEncoding === 'deflate'){
                comp=zlib.createDeflate()
            }
           else if(compressionEncoding === 'br'){
                comp=zlib.createBrotliCompress()
            }
            fileStream.pipe(comp).pipe(res)
        }else{
            fileStream.pipe(res)
        }
      } else {
        res.end()
      }
    }
  }
})
server.listen(3000, () => {
  console.log('server is running at http://localhost:3000')
})